package com.hoshiicloud.saleorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.QueryException;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.saleorder.entity.Payorder;
import com.hoshiicloud.saleorder.feign.IdGeneratorService;
import com.hoshiicloud.saleorder.mapper.PayorderMapper;
import com.hoshiicloud.saleorder.service.PayorderService;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 支付订单 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-03
 */
@Slf4j
@Service
public class PayorderServiceImpl extends ServiceImpl<PayorderMapper, Payorder> implements
        PayorderService {

    @Autowired
    private IdGeneratorService idGeneratorService;

    /**
     * @param id
     * @return com.hoshiicloud.saleorder.entity.Payorder
     * @description: 根据id查询支付订单
     */
    @Override
    @Cacheable(cacheNames = "Payorder", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "销售订单-支付订单-查询支付订单 ")
    public Payorder getById(Long id) {
        return baseMapper.selectById(id);
    }

    /**
     * @param param
     * @return boolean
     * @description: 新增支付订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "Payorder", allEntries = true)
    @Logable(authName = "销售订单-支付订单-新增支付订单")
    public boolean save(Payorder entity) {

        return Optional.ofNullable(entity).map(payorder -> {
//            String id = idGeneratorService.queryGeneratorId();
//            if (StrUtil.isBlank(id)) {
//                throw new ServiceException(CommonError.error("新增支付订单失败"));
//            }
//            entity.setId(Long.parseLong(id));

            entity.setCreatedTime(LocalDateTime.now());
            int row = baseMapper.insert(entity);
            if (row <= 0) {
                throw new ServiceException(CommonError.error("新增支付订单失败"));
            }

            return true;
        }).orElseThrow(() -> new ServiceException(CommonError.error("新增支付订单失败，保存对象为空")));
    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改支付订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "Payorder", allEntries = true)
    @Logable(authName = "销售订单-支付订单管理-修改支付订单")
    public boolean updateById(Payorder entity) {

        entity.setUpdatedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改失败"));
        }
        return true;
    }

    /**
     * @param key
     * @return IPage
     * @description: 分页查询支付订单
     */
    @Override
    @Logable(authName = "销售订单-支付订单管理-分页查询支付订单")
    @Cacheable(cacheNames = "Payorder", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+ T(com.hoshiicloud.common.utils.DigestUtils).md5(#key)")
    public IPage<Payorder> page(IPage<Payorder> page, Wrapper<Payorder> queryWrapper, String key) {
        try {
            return baseMapper.selectPage(page, queryWrapper);
        } catch (Exception e) {
            log.error("分页查询支付订单异常 {}", e.getMessage());
            throw new ServiceException("分页查询支付订单异常");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "Payorder", allEntries = true)
    @Logable(authName = "销售订单-支付订单管理-删除支付订单")
    public boolean deleteById(Long id) {
        Payorder entity = this.getById(id);

        return Optional.ofNullable(entity).map(payorder -> {
            payorder.setUpdatedTime(LocalDateTime.now());
            int row = baseMapper.updateById(payorder);
            if (row <= 0) {
                throw new ServiceException(CommonError.error("删除支付订单失败"));
            }
            return true;
        }).orElseThrow(() -> {
            log.error("删除支付订单异常，删除支付订单记录");
            return new QueryException("删除支付订单异常，删除支付订单记录");
        });
    }

    @Override
    @Cacheable(cacheNames = "Payorder", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "销售订单-支付订单管理-根据id集合查询支付订单")
    public List<Payorder> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }
}
